package com.aeromedia.testcustomapplication

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.aeromedia.custom_service_android_demo.call.CallActivityA
import com.aeromedia.testcustomapplication.recyclerVIew.CustomServiceAdapter
import com.aeromedia.vh_sdk.repository.RoomClientRepository
import kotlinx.android.synthetic.main.fragment_four_custom_service.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class FourCustomServiceFragment : Fragment() {
    val viewModel by activityViewModels<FourCustomServiceViewModel>()

    val customServiceAdapter: CustomServiceAdapter by lazy {
        CustomServiceAdapter(context)
    }

    override fun onCreateView(inflater: LayoutInflater,
                              container: ViewGroup?, savedInstanceState: Bundle?): View? {
        Log.d(TAG, "onCreateView: ")
        return inflater.inflate(R.layout.fragment_four_custom_service, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        Log.d(TAG, "onViewCreated: start")
        recycler_view.layoutManager = LinearLayoutManager(context)
        recycler_view.adapter = customServiceAdapter

        customServiceAdapter.setItemClickListener { data, position ->
            if (data.state == null || data.state == CustomServiceUser.State.OFFLINE) {
                return@setItemClickListener
            }
            val call = viewModel.makeCall(data.userId)
            context?.let { CallActivityA.open(it, call) }
        }

        viewModel.userList.observe(viewLifecycleOwner, Observer {
            Log.d(TAG, "onViewCreated: ")
            customServiceAdapter.data = it
        })

        Log.d(TAG, "onViewCreated:  lifecycleScope.launch ")
        lifecycleScope.launch {
            while (true) {
                delay(2000)
                val data = customServiceAdapter.data
                if (!data.isNullOrEmpty()) {
                    val map = data.stream().map {
                        it.userId
                    }.toArray<String> { value -> arrayOfNulls(value) }

                    Log.d(TAG, "onViewCreated: map:$map")
                    RoomClientRepository.getStates(map) { res ->
                        viewModel.updateData(res)

                    }
                }
                delay(3000)
            }
        }

        Log.d(TAG, "onViewCreated:viewModel.getData ")
        viewModel.getData()


    }

    companion object {
        private const val TAG = "FourCustomServiceFragme"
    }
}